<script setup lang="ts">
  import { useI18n } from 'vue-i18n';
  import { computed, nextTick, reactive, ref, watchEffect, Ref } from 'vue';
  import { Message, Modal, TableColumnData } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  import { removeMenu, selectMenuList } from '@/api/menu';
  import Icon from '@/components/icon/index.vue';
  import AddModal from '@/views/system/permission/components/add-modal.vue';
  import { MenuResp } from '@/api/menu/types';
  import useConfirmDialog from '@/hooks/dialog';

  // 加载状态
  const { loading, setLoading } = useLoading(true);
  const { t } = useI18n();
  const menuStatusFieldNames = { value: 'value', label: 'label' };

  // 菜单状态选项
  const menuStatusOptions = ref<{ label: string; value: number }[]>([
    {
      label: '全部',
      value: -1,
    },
    {
      label: '启用',
      value: 1,
    },
    {
      label: '禁用',
      value: 0,
    },
  ]);

  // 类型定义
  type SizeProps = 'mini' | 'small' | 'medium' | 'large';
  const size = ref<SizeProps>('medium');

  // 选择密度处理函数
  const handleSelectDensity = (
    val: SizeProps, // 这里使用 SizeProps 类型
    e: Event,
  ) => {
    size.value = val;
  };

  // 密度列表计算属性
  const densityList = computed(() => [
    {
      name: t('searchTable.size.mini'),
      value: 'mini' as SizeProps, // 这里使用类型断言
    },
    {
      name: t('searchTable.size.small'),
      value: 'small' as SizeProps, // 这里使用类型断言
    },
    {
      name: t('searchTable.size.medium'),
      value: 'medium' as SizeProps, // 这里使用类型断言
    },
    {
      name: t('searchTable.size.large'),
      value: 'large' as SizeProps, // 这里使用类型断言
    },
  ]);

  // 用户信息列表列配置
  const columns: TableColumnData[] = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      align: 'center',
    },
    {
      title: '类型',
      dataIndex: 'menuType',
      align: 'center',
      slotName: 'menuType',
    },
    {
      title: '图标',
      dataIndex: 'icon',
      align: 'center',
      slotName: 'icon',
    },
    {
      title: '权限标识',
      dataIndex: 'permission',
      align: 'center',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '组件地址',
      dataIndex: 'component',
      align: 'center',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '认证',
      dataIndex: 'requiresAuth',
      align: 'center',
      slotName: 'requiresAuth',
    },
    {
      title: '国际化标识',
      dataIndex: 'locale',
      align: 'center',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '排序',
      dataIndex: 'order',
      align: 'center',
    },
    {
      title: '顶部导航',
      dataIndex: 'noAffix',
      align: 'center',
      slotName: 'noAffix',
    },
    {
      title: '缓存',
      dataIndex: 'ignoreCache',
      align: 'center',
      slotName: 'ignoreCache',
    },
    {
      title: '路由',
      dataIndex: 'path',
      align: 'center',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: '路由名称',
      dataIndex: 'routerName',
      align: 'center',
    },
  ];
  const tableRef = ref();
  const addModalRef = ref();
  // 菜单列表
  const menuList: Ref<MenuResp[]> = ref([]);
  // 选中行的ID
  const selectedRowKeys: Ref<number[]> = ref([]);
  // 请求参数类型
  const params = ref<{
    menuName: string;
    enable: number; // -1 表示所有，1 表示启用，0 表示禁用
  }>({
    menuName: '',
    enable: -1,
  });

  // 获取菜单列表
  const getMenuList = async (): Promise<void> => {
    // 声明返回值类型为 Promise<void>
    setLoading(true);
    try {
      const result = await selectMenuList(params.value);
      menuList.value = result.data; // 假设 result.data 为 MenuResp[]
    } finally {
      setLoading(false);
    }
  };

  // 初始加载菜单列表
  getMenuList();

  // 查询函数
  const handleSearch = (): void => {
    // 声明返回值类型为 void
    getMenuList();
  };

  // 重置函数
  const handleReset = (): void => {
    // 声明返回值类型为 void
    params.value.menuName = '';
    params.value.enable = -1;
    getMenuList();
    // 重置复选框
    tableRef.value?.select(selectedRowKeys.value, false);
  };
  // 刷新函数
  const handleReFresh = (): void => {
    // 声明返回值类型为 void
    getMenuList();
  };

  // 删除函数
  const handleDelete = async (): Promise<void> => {
    // 声明返回值类型为 Promise<void>
    if (selectedRowKeys.value.length > 0) {
      useConfirmDialog({
        title: '确认删除',
        content: '你确定要删除这条数据吗？',
        onOk: async () => {
          // 在这里执行删除数据的逻辑
          await removeMenu(selectedRowKeys.value);
          Message.success('删除成功');
          // 重新获取菜单列表
          await getMenuList();
        },
      });
    } else {
      Message.error('请至少选中一行数据！');
    }
  };
  // 标签颜色函数
  const menuTypeColor = (menuType: number): string => {
    // 声明返回值类型为 string
    if (menuType === 0) {
      return 'green';
    }
    if (menuType === 1) {
      return 'blue';
    }
    return 'orange';
  };
  // 行展开/折叠标识
  const expandTag = ref<boolean>(false); // 指定类型为 boolean
  watchEffect(() => {
    tableRef.value?.expandAll(expandTag.value);
  });
  // 表格的行选择配置
  const rowSelection = computed(() => ({
    type: 'checkbox' as const,
    checkStrictly: true,
    onlyCurrent: false,
    showCheckedAll: true,
  }));
  // 新增菜单
  const dialogVisiable = ref(false);
  // 保存成功回调函数
  const handleSaveSuccess = () => {
    dialogVisiable.value = false;
    getMenuList();
  };
  // 编辑菜单
  const handleEdit = () => {
    if (selectedRowKeys.value.length === 1) {
      addModalRef.value?.handleEdit(selectedRowKeys.value[0]);
      dialogVisiable.value = true;
    } else {
      Message.error('请选中一行数据！');
    }
  };
</script>

<template>
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="params"
        label-align="left"
        :label-col-props="{ span: 6 }"
        layout="inline"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="username" label="菜单名称：" label-col-flex="70px">
          <a-input v-model="params.menuName" placeholder="请输入菜单名称" />
        </a-form-item>
        <a-form-item field="status" label="状态：" label-col-flex="70px">
          <a-select
            v-model="params.enable"
            :options="menuStatusOptions"
            :field-names="menuStatusFieldNames"
            placeholder="请选择菜单状态"
            :style="{ width: '180px' }"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              v-permission="'system:menu:list'"
              type="primary"
              @click="handleSearch"
            >
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button type="primary" @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px; margin-bottom: 16px" />
  <a-row style="margin-bottom: 16px">
    <a-col :span="12">
      <a-space>
        <a-button type="secondary" @click="expandTag = !expandTag">
          <template #icon>
            <icon-expand />
          </template>
          {{ '展开/折叠' }}
        </a-button>
        <a-button
          v-permission="'system:menu:add'"
          type="primary"
          @click="dialogVisiable = true"
        >
          <template #icon>
            <icon-plus />
          </template>
          {{ $t('searchTable.operation.create') }}
        </a-button>
        <a-button
          v-permission="'system:menu:edit'"
          type="primary"
          :disabled="selectedRowKeys.length !== 1"
          @click="handleEdit"
        >
          <template #icon>
            <icon-edit />
          </template>
          {{ $t('searchTable.operation.edit') }}
        </a-button>
        <a-button
          v-permission="'system:menu:remove'"
          type="primary"
          status="danger"
          @click="handleDelete"
        >
          <template #icon>
            <icon-delete />
          </template>
          {{ $t('searchTable.operation.remove') }}
        </a-button>
      </a-space>
    </a-col>
    <a-col
      :span="12"
      style="display: flex; align-items: center; justify-content: end"
    >
      <a-space :size="12">
        <a-button>
          <template #icon>
            <icon-download />
          </template>
          {{ $t('searchTable.operation.download') }}
        </a-button>
        <a-tooltip
          :content="$t('searchTable.actions.refresh')"
          @click="handleReFresh"
        >
          <div class="action-icon">
            <icon-refresh size="18" />
          </div>
        </a-tooltip>
        <a-dropdown @select="handleSelectDensity">
          <a-tooltip :content="$t('searchTable.actions.density')">
            <div class="action-icon">
              <icon-line-height size="18" />
            </div>
          </a-tooltip>
          <template #content>
            <a-doption
              v-for="item in densityList"
              :key="item.value"
              :value="item.value"
              :class="{ active: item.value === size }"
            >
              <span>{{ item.name }}</span>
            </a-doption>
          </template>
        </a-dropdown>
      </a-space>
    </a-col>
  </a-row>
  <a-row style="flex: 1">
    <a-col :span="24">
      <a-table
        ref="tableRef"
        v-model:selected-keys="selectedRowKeys"
        row-key="id"
        :loading="loading"
        :scroll="{ y: 'calc(100vh - 311px)' }"
        :columns="columns"
        :data="menuList"
        :bordered="false"
        :size="size"
        table-layout-fixed
        :column-resizable="true"
        :row-selection="rowSelection"
      >
        <template #menuType="{ record }">
          <a-tag :color="menuTypeColor(record.menuType)">
            {{
              record.menuType === 0
                ? '目录'
                : record.menuType === 1
                  ? '菜单'
                  : '按钮'
            }}
          </a-tag>
        </template>
        <template #icon="{ record }">
          <Icon :type="record.icon"></Icon>
        </template>
        <template #requiresAuth="{ record }">
          <a-tag
            v-show="record.requiresAuth !== null"
            :color="record.requiresAuth ? 'green' : 'red'"
          >
            {{ record.requiresAuth ? '需要' : '否' }}
          </a-tag>
        </template>
        <template #noAffix="{ record }">
          <a-tag
            v-show="record.noAffix !== null"
            :color="!record.noAffix ? 'green' : 'red'"
          >
            {{ !record.noAffix ? '是' : '否' }}
          </a-tag>
        </template>
        <template #ignoreCache="{ record }">
          <a-tag
            v-show="record.ignoreCache !== null"
            :color="!record.ignoreCache ? 'green' : 'red'"
          >
            {{ !record.ignoreCache ? '是' : '否' }}
          </a-tag>
        </template>
      </a-table>
    </a-col>
  </a-row>
  <!--新增菜单modal-->
  <add-modal
    ref="addModalRef"
    :dialog-visiable="dialogVisiable"
    @dialog-status="(value: boolean) => (dialogVisiable = value)"
    @save-success="handleSaveSuccess"
  ></add-modal>
</template>

<style scoped lang="less">
  .action-icon {
    cursor: pointer;
  }
</style>
